package com.kuyou.publiclibrary.utils;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * BLEUtils
 * 2021-4-1    cby:ZR
 */
public class BLEUtils extends BaseUtils{

    private final String TAG = "BLEUtils";

    private BLECallback bleCallback;


    //设备已连接
    private   boolean isConnect = false  ;
    private   boolean isScanService= false;

    private static  BLEUtils instance = new BLEUtils();

    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            isScan = true;
            Log.d(TAG,device.getAddress());
           // Log.d(TAG,isScan+"");
            if(device.getName()!= null){
                Log.d(TAG,device.getName());
                if(device.getName().startsWith(deviceName)){
                    if(isScanService){
                        return;
                    }
                    mdevice= device;
                    connectGATT(mdevice,serviceId,bleCallback);
                    isScanService = true;
                    adapter.stopLeScan(leScanCallback);
                }
            }

        }

    };
    private String deviceName="无";
    private String serviceId="0000000";


    private Context _context;
    private Activity _activity;
    private BluetoothManager manager;
    private BluetoothAdapter adapter;
    private BluetoothLeScanner scanner;
    private BluetoothGatt bluetoothGatt;
    private boolean isScan = false;
    private UUID uuid;
    private BluetoothGattCharacteristic service;
    private BluetoothDevice mdevice;


    public static BLEUtils getInstance() {
        return instance;
    }

    public boolean init(Context context){
        //初始化manager
        try {
            this._context = context;
            manager = (BluetoothManager) _context.getSystemService(Context.BLUETOOTH_SERVICE);
            assert manager != null;
            //初始化adapter
            adapter = manager.getAdapter();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  true;
    }
    public void sendData(byte [] data){
        try {
            if(isConnect){
                service.setValue(data);
                bluetoothGatt.writeCharacteristic(service);
            }
        }catch (Exception e){

        }


    }


    public boolean IsConnect(){
        return isConnect;

    }
    public boolean disConnect(){
        try {
            bluetoothGatt.disconnect();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  true;
    }



    public boolean connect(Activity activity,String deviceName,String mService,BLECallback bleCallback){
        _activity = activity;
        this.bleCallback = bleCallback;
        this.serviceId = mService;
        this.deviceName = deviceName;
        try {
            if(!adapter.isEnabled() ){

                adapter.enable();

            }
            adapter.startLeScan(leScanCallback);
        }catch (Exception e){
            e.printStackTrace();
        }

        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {


                adapter.stopLeScan(leScanCallback);
                if(bluetoothGatt!=null){
                    //如果已连接就直接返回

                    return  ;
                }

                isScan = false;
                _activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(_context,"未找到设备，请开启设备",Toast.LENGTH_SHORT).show();

                    }
                });
            }
        };
        timer.schedule(timerTask,40000);
        return  false;
    }

    public boolean connectGATT(BluetoothDevice device, final String mService, final BLECallback bleCallback){

        bluetoothGatt = device.connectGatt(_context, false, new BluetoothGattCallback() {
            @Override
            public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
                super.onPhyUpdate(gatt, txPhy, rxPhy, status);
            }

            @Override
            public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
                super.onPhyRead(gatt, txPhy, rxPhy, status);
            }

            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                super.onConnectionStateChange(gatt, status, newState);
                Log.e(TAG, "链接状态改变"+status+" "+newState);


                if (newState == BluetoothProfile.STATE_CONNECTED) {
                   bluetoothGatt.discoverServices();
                    Log.e(TAG, "开始扫描服务");
                }
                if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    bluetoothGatt.close();
                    bleCallback.onDisconnect();
                    isConnect =false;
                    Log.e(TAG, "断开连接");
                }


            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                super.onServicesDiscovered(gatt, status);

                    Log.d(TAG, "onservicesdiscovered收到: " + status);
                    for (BluetoothGattService a:gatt.getServices()) {
                            for(BluetoothGattCharacteristic characteristic: a.getCharacteristics()){
                                if(String.valueOf(characteristic.getUuid()).contains(mService)){
                                    Log.d(TAG, "找到服务:"+characteristic.getUuid().toString());
                                    service = characteristic;
                                    bluetoothGatt.setCharacteristicNotification(service, true);
                                    BluetoothGattDescriptor descriptor = service.getDescriptors().get(0);
                                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                                    bluetoothGatt.writeDescriptor(descriptor);
                                    bluetoothGatt.readCharacteristic(service);
                                    isConnect = true;
                                    bleCallback.onConnect();
//                                    Log.d("设置通知", "成功");
                                }
                            }
                    }

            }

            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                super.onCharacteristicRead(gatt, characteristic, status);
            }

            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                super.onCharacteristicWrite(gatt, characteristic, status);
            }

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                super.onCharacteristicChanged(gatt, characteristic);
                Log.d("收到notify", String.valueOf(characteristic.getValue()));
                bleCallback.onRecive(characteristic.getValue());
            }

            @Override
            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                super.onDescriptorRead(gatt, descriptor, status);
            }

            @Override
            public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                super.onDescriptorWrite(gatt, descriptor, status);
            }

            @Override
            public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
                super.onReliableWriteCompleted(gatt, status);
            }

            @Override
            public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
                super.onReadRemoteRssi(gatt, rssi, status);
            }

            @Override
            public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
                super.onMtuChanged(gatt, mtu, status);
            }
        });



        return  false;
    }


    public interface BLECallback{
        void onRecive(byte[] data);

        void onDisconnect();

        void onConnect();

    }

}
